package com.athena.tomcat;

import com.athena.config.DefaultAppConfig;
import com.athena.framework.web.RedisSessionHandlerValve;
import com.athena.framework.web.RedisSessionManager;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TomcatServer {

    private final static Logger logger = LoggerFactory.getLogger(TomcatServer.class);

    /**
     * 启动tomcat服务
     * @throws LifecycleException
     */
    public void  startServer() throws LifecycleException {
        //设置工作目录
        String catalina_home = DefaultAppConfig.catalinaHome;
        Tomcat tomcat = new Tomcat();
        tomcat.setHostname(DefaultAppConfig.hostname);
        tomcat.setPort(DefaultAppConfig.port);
        tomcat.setBaseDir(catalina_home);
        tomcat.getHost().setAutoDeploy(false);

        StandardContext context = new StandardContext();
        context.addValve(new RedisSessionHandlerValve());
        context.setManager(new RedisSessionManager());
        context.setPath("");
        context.addLifecycleListener(new Tomcat.FixContextListener());
        tomcat.getHost().addChild(context);
        //添加监听
        FilterDef filterDefinition = new FilterDef();
        filterDefinition.setFilterName(URLFilter.class.getSimpleName());
        filterDefinition.setFilterClass(URLFilter.class.getName());
        context.addFilterDef(filterDefinition);

        FilterMap filter1mapping = new FilterMap();
        filter1mapping.setFilterName(URLFilter.class.getSimpleName());
        filter1mapping.addURLPattern("/*");
        context.addFilterMap(filter1mapping);

        Tomcat.addServlet(context, "routeServlet", new RouteServlet());
        context.addServletMappingDecoded("/*", "routeServlet");

        //启动服务
        tomcat.start();
        if (logger.isInfoEnabled()){
            logger.info("tomcat服务已启动。。。");
        }
        tomcat.getServer().await();
    }
}
